<template>
  <div class="shop-login">
    <div class="shop-login-from">
      欢迎登录 <br>
      <el-form ref="from" :model="from" :rules="rules"
               style="margin-left: 50px;margin-right: 50px;margin-top: 20px;">
        <el-form-item prop="username">
          <el-input v-model="from.username" placeholder="请输入用户名"
                    prefix-icon="el-icon-user-solid">
            <template #prefix>
              <el-icon class="el-input__icon">
                <Avatar/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password" style="margin-bottom: 20px">
          <el-input v-model="from.password" placeholder="请输入用户密码"
                    prefix-icon="el-icon-lock" show-password clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <Unlock/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="code" style="">

          <el-input
              placeholder="验证码"
              v-model="from.code"
              clearable

              style="width: 255px;display: inline-block;"

          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <chat-dot-round/>
              </el-icon>
            </template>
          </el-input>
          <div class="code" @click="refreshCode" style="display: inline-block;vertical-align: bottom;margin-left: 20px">
            <security :identifyCode="identifyCode" style="height: 40px"></security>
          </div>

        </el-form-item>


        <el-button type="primary" round style="font-size: 20px;width: 400px;text-align: center;margin-top: 20px;
        " @click="submitForm()">登录
        </el-button>

        <router-link to="/register" style="font-size: 16px;float: right;margin-top: 10px;margin-right: 10px">去注册</router-link>

      </el-form>

    </div>

  </div>
</template>

<script>

import {Avatar, Unlock, ChatDotRound} from '@element-plus/icons-vue'
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import security from '@/components/code'

export default {
  name: "login",
  data() {
    return {

      // 随机抽取四位数
      identifyCodes: '1234567890abcdef',
      identifyCode: '',
      checked: false
      ,
      from: {
        username: "",
        password: "",
        //验证码相关
        code: '',

      },
      massages: {
        massageDefault: '',//默认灰色
        massageSuccess: 'success',//成功绿色
        massageWarning: 'warning',//警告黄色
        // 红色错误，不使用第二个参数即可
      },//定义顶部弹窗的四种状态
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          }
        ],
        password: [
          {
            required: true,
            message: '请输入用户密码',
            trigger: 'blur',
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur',
          }
        ]

      }
    }
  },
  mounted() {
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  components: {
    Avatar,
    Unlock,
    security,
    ChatDotRound
  }
  ,
  methods: {
    //验证码相关函数
    // 验证码处理
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },

    // 刷新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    //重新画图
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
            this.randomNum(0, this.identifyCodes.length)
            ]
      }
      console.log(this.identifyCode)
    },
    //提示栏函数
    open(massage, type) {

      if (type) {
        ElMessage({
          message: massage,
          type: type,
        })
      } else {
        ElMessage.error(massage)
      }
    },
    //表单提交
    submitForm() {
      this.$refs['from'].validate((valid) => {

        if (valid) {

          if (this.identifyCode === this.from.code) {
            request.post("http://localhost:8080/boot/user/login", this.from).then(res => {
              if (res.code === 200 && res.data) {

                //模拟登录成功，存放假数据，实际中应该使用JWT进行生成加密token
                //然后在通过请求参数进行传递，并且在发送请求时，都要携带这个token，
                // 然后在后端进行验证，JWT生成的token中，可以保存一些基本用户信息及标识
                // 分布式中的用户识别(session共享问题)解决方案之一

                window.sessionStorage.setItem('user', JSON.stringify(res.data))

                this.open("登录成功", this.massages.massageSuccess)

                this.$router.push("/home")//登录成功跳转页面
              } else {
                this.open("登录失败" + res.message)
              }
            }).catch(_ => {
              this.open("登录失败，请稍后重试")
              console.log(this.from)
            })//校验成功后，在进行登录
          }else {
            this.open("验证码错误");
            return false
          }
        }else {
            return false
        }


      })
    },
    //清空提示信息
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
  login2() {
    //使用自己封装的工具，不推荐使用以下方式发送post请求参数
    //let urlSearchParams = new URLSearchParams();
    //urlSearchParams.append("username",this.from.username);
    //urlSearchParams.append("password",this.from.password)
    // `username=${this.from.username}&password=${this.from.password}`

    //此处方法提到submitForm中了

    /* axios.post("http://localhost:8080/boot/user/login",{
       username: "老王",
       password: "123",
     }).then(res=>{
       console.log("成功了",res)
     }).catch(err=>{
       console.log("失败了",err)
     })*/
  }


}
</script>

<style scoped>
.shop-login {
  overflow: hidden;
  height: 100vh;
  width: 100%;
  background: #83a4d4;
  background: -webkit-linear-gradient(to right, #b6fbff, #83a4d4);
  background: linear-gradient(to right, #b6fbff, #83a4d4);
}

.shop-login-from {
  overflow: hidden;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 500px;
  height: 400px;
  margin: 8% auto;

  font-size: 34px;
  font-weight: bold;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  padding-top: 100px;

  color: #5e666f;

}


</style>